<template>
  <el-drawer v-model="dialogVisible" :title="dialogTitle" direction="rtl" size="30%">
    <el-form ref="formRef" :model="tableItem" :rules="rules" label-width="120px" :disabled="!isDisabled">
      <el-form-item label="分组名称" prop="groupName">
        <el-input v-model="tableItem.groupName" placeholder="请输入分组名称" />
      </el-form-item>

      <el-form-item label="用途" prop="usage">
        <el-select v-model="tableItem.usage" placeholder="请选择用途" style="width: 100%" @change="handleUsageChange">
          <el-option label="自用" value="自用" />
          <el-option label="公摊" value="公摊" />
        </el-select>
      </el-form-item>

      <el-form-item label="分组编码" prop="groupCode">
        <el-autocomplete v-model="tableItem.groupCode" :fetch-suggestions="queryGroupCodeList" placeholder="请输入分组编码进行搜索"
          style="width: 100%" :trigger-on-focus="false" @blur="handleGroupNumberBlur" @select="handleGroupNumberSelect"
          v-loading="checkingGroupNumber" clearable>
          <template #default="{ item }">
            <div class="group-suggestion-item">
              <div class="group-number">编码：{{ item.groupCode }}</div>
              <div class="group-info">
                <span class="group-name">名称：{{ item.groupName }}</span>
                <span class="unit-price">计费单价：{{ item.unitPrice }}元/m²</span>
              </div>
            </div>
          </template>
        </el-autocomplete>
      </el-form-item>

      <el-form-item label="计费单价" prop="billingMethod">
        <div style="display: flex; align-items: center; gap: 8px;">
          <el-input-number v-model="tableItem.billingMethod" :precision="2" :step="0.01" :min="0" style="width: 200px"
            controls-position="right" />
          <span>元/m²</span>
        </div>
      </el-form-item>

      <el-form-item label="比例" prop="proportion">
        <div style="display: flex; align-items: center; gap: 8px;">
          <el-input-number v-model="tableItem.proportion" :precision="1" :step="0.1" :min="0" :max="100"
            style="width: 200px" controls-position="right" />
          <span>%</span>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div style="flex: auto">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button v-if="dialogStatus !== 'view'" type="primary" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>
<script lang="ts" setup>
import { reactive, ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { existByGroupCode, getGroupListByCode } from '@/api/settle'
import type { MrsGroupQueryByCodeRequest } from '@/api/types/rent'

const emit = defineEmits(['listChange', 'createGroup', 'updateGroup'])

const dialogVisible = ref(false)
const dialogStatus = ref('create') // create, edit, view
const isDisabled = ref(true)
const groupId = ref('')
const currentEnterpriseId = ref('') // 当前选中的企业ID
const formRef = ref()
const usage_type_shared = '公摊'

const tableItem = reactive({
  groupName: '',
  groupCode: '',
  usage: '',
  billingMethod: 0,
  proportion: 0,
})

const checkingGroupNumber = ref(false); // 检查分组编码状态

// 设置当前企业ID的方法
const setEnterpriseId = (enterpriseId: string) => {
  currentEnterpriseId.value = enterpriseId
}

// 处理用途变化
const handleUsageChange = (value: string) => {
  // 如果不是公摊用途，隐藏导入选项
  if (value !== usage_type_shared) {
    tableItem.proportion = 100
  }
};

// 处理分组编码失焦事件
const handleGroupNumberBlur = () => {
  const groupCode = tableItem.groupCode?.trim();

  // 只有在公摊用途且有分组编码时才检查
  if (tableItem.usage === usage_type_shared || !groupCode) {
    return;
  }
  // 如果是编辑模式且编码没有变化，不需要检查
  if (dialogStatus.value === "edit" && groupCode === tableItem.groupCode) {
    return;
  }

  checkGroupNumberExists(groupCode);
};

// 检查分组编码是否存在
const checkGroupNumberExists = async (groupCode: string) => {
  checkingGroupNumber.value = true;

  try {    
    // 构建查询参数
    const queryData: MrsGroupQueryByCodeRequest = {
      enterpriseId: Number(currentEnterpriseId.value), // 企业ID
      groupCode: groupCode
    }
    // API调用检查分组编码
    const response = await existByGroupCode(queryData);
    if (response.success && response.data) {
      console.log("检测到分组编码已存在，请重新输入");
      // 分组编码存在
      ElMessage.warning(
        `检测到分组编码 "${groupCode}" 已存在，请重新输入`
      );
    } else {
      console.log("检测到分组编码不存在");
    }
  } catch (error) {
    ElMessage.error("检查分组编码失败，请稍后重试");
  } finally {
    checkingGroupNumber.value = false;
  }
};

// 查询分组编码建议列表
const queryGroupCodeList = async (queryString: string, callback: (suggestions: any[]) => void) => {
  if (!queryString || tableItem.usage !== usage_type_shared) {
    callback([]);
    return;
  }
  checkingGroupNumber.value = true;
  // 构建查询参数
  const queryData: MrsGroupQueryByCodeRequest = {
    objectType: '房租',
    groupCode: queryString
  }
  // API调用检查分组编码
  const response = await getGroupListByCode(queryData);
  console.log('查询分组编码建议结果:', response)
  if (response.success && response.data) {
    console.log('查询分组编码建议列表:', response.data)
    checkingGroupNumber.value = false;
    callback(response.data);
  }
};

// 处理分组编码选择
const handleGroupNumberSelect = (item: any) => {
  tableItem.groupName = item.groupName;
  tableItem.groupCode = item.groupCode;
  tableItem.billingMethod = item.unitPrice;
};

const rules = {
  groupName: [
    { required: true, message: '请输入分组名称', trigger: 'blur' }
  ],
  groupCode: [
    { required: false, message: '请输入分组编码', trigger: 'blur' }
  ],
  usage: [
    { required: true, message: '请选择租期类型', trigger: 'change' }
  ],
  billingMethod: [
    { required: true, message: '请输入计费单价', trigger: 'blur' }
  ],
  proportion: [
    { required: true, message: '请输入比例', trigger: 'blur' }
  ],
}

const dialogTitle = computed(() => {
  switch (dialogStatus.value) {
    case 'create':
      return '新增分组'
    case 'edit':
      return '编辑分组'
    case 'view':
      return '查看分组'
    default:
      return '分组信息'
  }
})

const reset = () => {
  Object.assign(tableItem, {
    groupName: '',
    groupCode: '',
    usage: '',
    billingMethod: 0,
    proportion: 0
  })
  formRef.value?.clearValidate()
}

const handleSubmit = () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (dialogStatus.value === 'create') {
        console.log('创建分组:', tableItem)
        console.log('当前企业ID:', currentEnterpriseId.value)
        
        // 验证是否已选择企业
        if (!currentEnterpriseId.value) {
          ElMessage.error('请先选择企业')
          return
        }
        
        // 构建新增分组请求数据
        const groupAddRequest = {
          groupName: tableItem.groupName,
          groupCode: tableItem.groupCode || '',
          allocationRatio: Number(tableItem.proportion) || 0,
          enterpriseId: Number(currentEnterpriseId.value), // 使用当前选中的企业ID
          unitPrice: Number(tableItem.billingMethod) || 0,
          usageType: tableItem.usage === usage_type_shared ? 1 : 0, // 0=自用 1=公摊
          objectType: '房租' // 固定值
        }
        
        console.log('新建分组数据:', groupAddRequest)
        
        // 调用父组件的创建方法
        try {
          await emit('createGroup', groupAddRequest)
          dialogVisible.value = false
        } catch (error: any) {
          ElMessage.error(`创建分组失败: ${error.message || '未知错误'}`)
        }
        
      } else if (dialogStatus.value === 'edit') {
        console.log('编辑分组:', tableItem, '分组ID:', groupId.value)
        console.log('当前企业ID:', currentEnterpriseId.value)
        
        // 验证是否已选择企业
        if (!currentEnterpriseId.value) {
          ElMessage.error('请先选择企业')
          return
        }
        
        // 构建更新分组请求数据
        const groupUpdateRequest = {
          id: Number(groupId.value),
          groupName: tableItem.groupName,
          groupCode: tableItem.groupCode || '',
          allocationRatio: Number(tableItem.proportion) || 0,
          enterpriseId: Number(currentEnterpriseId.value), // 使用当前选中的企业ID
          unitPrice: Number(tableItem.billingMethod) || 0,
          usageType: tableItem.usage === usage_type_shared ? 1 : 0, // 0=自用 1=公摊
          objectType: '房租' // 固定值
        }
        
        console.log('更新分组数据:', groupUpdateRequest)
        
        // 调用父组件的更新方法
        try {
          await emit('updateGroup', groupUpdateRequest)
          dialogVisible.value = false
        } catch (error: any) {
          ElMessage.error(`更新分组失败: ${error.message || '未知错误'}`)
        }
      }
    }
  })
}

defineExpose({
  dialogVisible,
  dialogStatus,
  isDisabled,
  groupId,
  tableItem,
  reset,
  setEnterpriseId
})

</script>

<style lang="scss" scoped>
.existing-group-info {
  margin-top: 8px;  

  .group-details {
    margin-bottom: 12px;

    p {
      margin: 4px 0;
      font-size: 13px;
      color: #606266;

      strong {
        color: #303133;
      }
    }
  }

  .import-actions {
    display: flex;
    gap: 8px;
    margin-top: 8px;
  }
}

:deep(.el-alert__content) {
  padding-right: 0;
}

:deep(.el-input-number) {
  width: 100%;
}

.group-suggestion-item {
  padding: 8px 0;
  display: flex;
  
  .group-number {
    font-weight: bold;
    color: #409eff;
    font-size: 14px;
    margin-bottom: 4px;
  }
  
  .group-info {
    display: flex;
    gap: 12px;
    font-size: 12px;
    color: #666;
    margin-left: 10px;
    
    .group-name {
      color: #303133;
      font-weight: 500;
    }
    
    .rent-count {
      color: #67c23a;
    }
    
    .unit-price {
      color: #e6a23c;
    }
  }
}
</style>
